'use strict';
module.exports = (options, app) => {

  const jwt = require('jsonwebtoken');

  const noToken = [
    '/user/login',
    '/user/create',
  ];

  function decideHasToken(url) {
    let is = -1;
    // eslint-disable-next-line array-callback-return
    noToken.map(item => {
      // eslint-disable-next-line no-undef
      if (url.indexOf(item) > -1) {
        is++;
      }
    });
    return is;
  }

  async function check_token(ctx, next) {
    if (decideHasToken(ctx.request.url) > -1) {
      await next();
    } else if (ctx.request.header.token) {
      const token = ctx.request.header.token;
      let decoded;
      // 解码token
      try {
        decoded = jwt.verify(token, app.config.jwt.secret);
        const conn = ctx.app.redis.getConn('db0');
        const Rtoken = await ctx.app.redis.get(conn, `userid_${decoded.userid}`);
        ctx.app.redis.doRelease(conn);
        if (Rtoken !== token) {
          ctx.status = 401;
          ctx.body = {
            code: 401,
            message: 'token失效',
          };
          return;
        }
      } catch (error) {
        if (error.name === 'TokenExpiredError') {
          ctx.status = 401;
          ctx.body = {
            code: 401,
            message: 'token失效',
          };
          return;
        }
        ctx.status = 401;
        ctx.body = {
          code: 401,
          message: 'token失效',
        };
        return;

      }
      // 重置cookie时间
      ctx.cookies.set('token', token, {
        maxAge: 60 * 60 * 1000,
        httpOnly: false,
        overwrite: true,
        signed: false,
      });
      await next();
    } else {
      ctx.status = 401;
      ctx.body = {
        code: 401,
        message: '没有token',
      };
      return;
    }
  }

  return check_token;
};
